<?php
/**
 * @package YARBB
 * @copyright Авторские права (C) 2009 www.yar-it.com. Все права защищены.
 * @license Лицензия http://www.gnu.org/licenses/gpl-2.0.htm GNU/GPL, или help/license.php
 * YARBB! - свободное программное обеспечение распространяемое по условиям лицензии GNU/GPL
 * Для получения информации о используемых расширениях и замечаний об авторском праве, смотрите файл copyright.php.
 */
// don't allow direct linking
defined( '_VALID_MOS' ) or die();
// Cookie stuff!
/**
 * Checks user data
 * @param string User to check
 */

function check_user(&$yarbb_user) {
	global $db_type, $yarbb_config, $cookie_name, $cookie_seed, $mosConfig_lang, $my;

	$mainframe = mosMainFrame::getInstance();
	$database = $mainframe->getDBO();

	$now    = time();
	$expire = $now + 1800;	// The cookie expires after a year


	if ($my->id) {
		$sql='SELECT fu.*, g.*, uextra.*, o.logged, o.idle, juser.* FROM #__users as juser
		INNER JOIN #__forum_users AS fu ON fu.id=juser.id
		LEFT JOIN #__users_extra AS uextra ON uextra.user_id=juser.id
		INNER JOIN #__forum_groups AS g ON fu.group_id=g.g_id
		LEFT JOIN #__forum_online AS o ON o.user_id=fu.id WHERE juser.id='.$my->id;
		$database->setQuery($sql);
		$s=$database->loadAssocList();
		$yarbb_user = $s[0];


		if ($yarbb_user['block']==1) {
			echo "<script>alert(\""._LOGIN_BLOCKED."\"); window.history.go(-1); </script>\n";
			exit();
		}

		if (!$yarbb_user) {
			// Add the user
			$query = ('INSERT INTO #__forum_users (id) VALUES('.$my->id.')');
			$database->setQuery($query);
			$database->query();
			$new_uid = $database->insertid();

			$sql='SELECT u.*, g.*, o.logged, o.idle, juser.block FROM #__users as juser
				INNER JOIN #__forum_users AS u ON u.jos_id=juser.id
				LEFT JOIN #__users_extra AS uextra ON uextra.user_id=juser.id
				INNER JOIN #__forum_groups AS g ON u.group_id=g.g_id
				LEFT JOIN #__forum_online AS o ON o.user_id=u.id WHERE juser.id='.$my->id;
			$database->setQuery($sql);
			$s=$database->loadAssocList();
			$yarbb_user = $s[0];
		}


		// If user logged out of mambo (or his mambo session expired)
		if (!$my->id && !$yarbb_user['is_guest']) {
			YARBBlogout();
			set_default_user();
			return;
		}

		if (!$yarbb_user['disp_topics']) {
			$yarbb_user['disp_topics'] = $yarbb_config['o_disp_topics_default'];
		}

		if (!$yarbb_user['disp_posts']) {
			$yarbb_user['disp_posts'] = $yarbb_config['o_disp_posts_default'];
		}

		if ($yarbb_user['save_pass'] == '0') {
			$expire = 0;
		}

		// Define this if you want this visit to affect the online list and the users last visit data
		if (!defined('YARBB_QUIET_VISIT')) {
			// Update the online list
			if (!$yarbb_user['logged']) {
				$yarbb_user['logged'] = $now;
				//var_dump( $yarbb_user['logged'] );
				// With MySQL/MySQLi, REPLACE INTO avoids a user having two rows in the online table
				switch ($db_type) {
					case 'mysql':
					case 'mysqli':
					//s
						$database->setQuery('REPLACE INTO #__forum_online (user_id, ident, logged) VALUES('.$yarbb_user['id'].', \''.$database->getEscaped($yarbb_user['username']).'\', '.$yarbb_user['logged'].')');
						$database->query();
						break;
					default:
					//s?
						$database->setQuery('INSERT INTO #__forum_online (user_id, ident, logged, color) VALUES('.$yarbb_user['id'].', \''.$database->getEscaped($yarbb_user['username']).'\', '.$yarbb_user['logged'].', \''.$database->getEscaped($yarbb_user['g_color']).'\')');
						$database->query();
						break;
				}
			} else {
				// Special case: We've timed out, but no other user has browsed the forums since we timed out
				if ($yarbb_user['logged'] < $now - $yarbb_config['o_timeout_visit']) {
					//s
					$database->setQuery('UPDATE #__forum_users SET last_visit='.$yarbb_user['logged'].' WHERE id='.$yarbb_user['id']);
					$database->query();
					$yarbb_user['last_visit'] = $yarbb_user['logged'];
				}
				$idle_sql = ($yarbb_user['idle'] == '1') ? ', idle=0' : '';
				//var_dump( $idle_sql );
				$database->setQuery('UPDATE #__forum_online SET logged='.$now.$idle_sql.' WHERE user_id='.$yarbb_user['id']);
				$database->query();
			}
		}
		$yarbb_user['is_guest'] = false;
	} else {
		set_default_user();
	}
}
// заполнение настроек для гостя
function set_default_user() {
	global $database, $db_type, $yarbb_user, $yarbb_config, $mosConfig_lang,$database;
	$remote_addr = get_remote_address();

	$sql ='SELECT u.*, g.*, o.logged FROM #__forum_users AS u INNER JOIN #__forum_groups AS g ON u.group_id=g.g_id LEFT JOIN #__forum_online AS o ON o.ident=\''.$remote_addr.'\' WHERE u.id=1';
	$database->setQuery($sql);
	$u = $database->loadAssocList();
	$yarbb_user = $u[0];
	unset($u);

	if (!$yarbb_user['id']) {
		exit('Unable to fetch guest information. The table \'#__forum_users\' must contain an entry with id = 1 that represents anonymous users.');
	}

	/* boston ТУТ не знает чего делать... */
	// Update online list
	if (!$yarbb_user['logged']) {
		$yarbb_user['logged'] = time();
		// With MySQL/MySQLi, REPLACE INTO avoids a user having two rows in the online table
		echo $db_type;
		switch ($db_type) {
			case 'mysql':
			case 'mysqli':
			//$db->query('REPLACE INTO '.$db->prefix.'online (user_id, ident, logged) VALUES(1, \''.$db->escape($remote_addr).'\', '.$yarbb_user['logged'].')');
				break;
			default:
			//$db->query('INSERT INTO '.$db->prefix.'online (user_id, ident, logged, color) VALUES(1, \''.$db->escape($remote_addr).'\', '.$yarbb_user['logged'].' \''.$yarbb_user['g_color'].'\')');
				break;
		}
	}else {
		//$db->query('UPDATE '.$db->prefix.'online SET logged='.time().' WHERE ident=\''.$db->escape($remote_addr).'\'') ;
	}

	$yarbb_user['disp_topics'] = $yarbb_config['o_disp_topics_default'];
	$yarbb_user['disp_posts'] = $yarbb_config['o_disp_posts_default'];
	//$yarbb_user['timezone'] = $yarbb_config['o_server_timezone'];
	$yarbb_user['language'] = $mosConfig_lang;
	$yarbb_user['style'] = $yarbb_config['o_default_style'];
	$yarbb_user['is_guest'] = true;
}
// Set a cookie, YarBB style!
function yarbb_setcookie($user_id, $password_hash, $expire) {
	global $cookie_name, $cookie_path, $cookie_domain, $cookie_secure, $cookie_seed;
	if (version_compare(PHP_VERSION, '5.2.0', '>=')) {
		setcookie($cookie_name, serialize(array($user_id, md5($cookie_seed.$password_hash))), $expire, $cookie_path, $cookie_domain, $cookie_secure, true);
	}else {
		setcookie($cookie_name, serialize(array($user_id, md5($cookie_seed.$password_hash))), $expire, $cookie_path.'; HttpOnly', $cookie_domain, $cookie_secure);
	}
}
function ya_message($ya_message, $no_back_link = false) {
	global $database, $yarbb_config, $yarbb_start, $tpl_main, $yarbb_path;
	$ya_message;
}

// Check whether the connecting user is banned (and delete any expired bans while we're at it)
function check_bans() {
	global $database, $yarbb_config, $yarbb_user, $yarbb_bans;
	// Admins aren't affected
	if ($yarbb_user['g_id'] == YARBB_ADMIN || !$yarbb_bans)
		return;
	// Add a dot at the end of the IP address to prevent banned address 192.168.0.5 from matching e.g. 192.168.0.50
	$user_ip = get_remote_address().'.';
	$bans_altered = false;
	foreach ($yarbb_bans as $cur_ban) {
		// Has this ban expired?
		if ($cur_ban['expire'] != '' && $cur_ban['expire'] <= time()) {
			//s
			$database->setQuery('DELETE FROM #__forum_bans WHERE id='.$cur_ban['id']);
			$database->query();
			$bans_altered = true;
			continue;
		}
		if ($cur_ban['username'] != '' && !strcasecmp($yarbb_user['username'], $cur_ban['username'])) {
			$database->setQuery('DELETE FROM #__forum_online WHERE ident=\''.$database->getEscaped($yarbb_user['username']).'\'');
			$database->query();

			ya_message( _Y_BADMESSAGE.' '.(($cur_ban['expire'] != '') ? _Y_BADMESSAGE1.'
			 '.strtolower(format_time($cur_ban['expire'], true)).'. ' : '').(($cur_ban['message'] != '') 
					? _Y_BADMESSAGE2.'<br /><br /><strong>'.yarbb_htmlspecialchars($cur_ban['message']).'</strong><br /><br />'
					: '<br /><br />')._Y_BADMESSAGE3.' <a href="mailto:'.$yarbb_config['o_admin_email'].'">
			  '.$yarbb_config['o_admin_email'].'</a>.', true);
		}
		if ($cur_ban['ip'] != '') {
			$cur_ban_ips = explode(' ', $cur_ban['ip']);
			for ($i = 0; $i < count($cur_ban_ips); ++$i) {
				$cur_ban_ips[$i] = $cur_ban_ips[$i].'.';
				if (substr($user_ip, 0, strlen($cur_ban_ips[$i])) == $cur_ban_ips[$i]) {
					//s
					$database->setQuery('DELETE FROM #__forum_online WHERE ident=\''.$database->getEscaped($yarbb_user['username']).'\'');
					$database->query();

					ya_message(_Y_BADMESSAGE.' '.(($cur_ban['expire'] != '') ? _Y_BADMESSAGE1.' '.strtolower(format_time($cur_ban['expire'], true)).'. ' : '').(($cur_ban['message'] != '') ? _Y_BADMESSAGE2.'<br /><br /><strong>'.yarbb_htmlspecialchars($cur_ban['message']).'</strong><br /><br />' : '<br /><br />')._Y_BADMESSAGE3.' <a href="mailto:'.$yarbb_config['o_admin_email'].'">'.$yarbb_config['o_admin_email'].'</a>.', true);
				}
			}
		}
	}
	// If we removed any expired bans during our run-through, we need to regenerate the bans cache
	if ($bans_altered) {
		require_once $yarbb_admin_path.'/include/cache.php';
		generate_bans_cache();
	}
}
/**
 * Updates user online
 * Logged time is contantly updated
 */
function update_users_online() {
	global $database, $yarbb_config, $yarbb_user, $cur_user;
	$now = time();
	// Fetch all online list entries that are older than "o_timeout_online"
	//s
	$sql="SELECT * FROM #__forum_online WHERE logged < " .($now - $yarbb_config['o_timeout_online']). "'";
	$database->setQuery($sql);
	$cur_users = $database->loadAssocList();

	foreach ($cur_users as $cur_users) {
		// If the entry is a guest, delete it
		if ($cur_user['user_id'] == '1') {
			//s
			$database->setQuery('DELETE FROM #__forum_online WHERE ident=\''.$database->getEscaped($cur_user['ident']).'\'');
			$database->query();
		} else {
			// If the entry is older than "o_timeout_visit", update last_visit for the user in question, then delete him/her from the online list
			if ($cur_user['logged'] < ($now - $yarbb_config['o_timeout_visit'])) {
				//s
				$database->setQuery('UPDATE #__forum_users SET last_visit='.$cur_user['logged'].' WHERE id='.$cur_user['user_id']) ;
				$database->query();
				$database->setQuery('DELETE FROM #__forum_online WHERE user_id='.$cur_user['user_id']);
				$database->query();
			}
			else if ($cur_user['idle'] == '0')
				$database->setQuery('UPDATE #__forum_online SET idle=1 WHERE user_id='.$cur_user['user_id']);
			$database->query();
		}
	}
}

// рендеринг верхнего главного меню
function generate_navlinks() {
	global $yarbb_config, $yarbb_user, $yarbb_path;

	$links[] = '<ul>';
	$links[] = '<li><a href="'.sefRelToAbs(YARBB_URL).'">'._Y_INDEX.'</a></li>';
	if ($yarbb_config['o_rules'] == '1') {
		$links[] = '<li><a href="'.sefRelToAbs(YARBB_URL.'&amp;task=misc&amp;action=rules').'">'._Y_RULESYAR.'</a></li>';
	}
	if ($yarbb_user['is_guest']) {
		if ($yarbb_user['g_search'] == '1')
			$links[] = '<li><a href="'.sefRelToAbs(YARBB_URL.'&amp;task=search').'">'._Y_SEARCH_TITLE.'</a></li>';

		$info = _DO_LOGIN;
	}else {
		if ($yarbb_user['g_id'] > YARBB_MOD) {
			if ($yarbb_user['g_search'] == '1') {
				$links[] = '<li><a href="'.sefRelToAbs(YARBB_URL.'&amp;task=search').'">'._Y_SEARCH_TITLE.'</a></li>';
			}
			$links[] = '<li><a href="'.sefRelToAbs(YARBB_URL.'&amp;task=profile&amp;id='.$yarbb_user['id']).'">'._Y_YPROFILE.'</a></li>';

		}else {
			$links[] = '<li><a href="'.sefRelToAbs(YARBB_URL.'&amp;task=search').'">'._Y_SEARCH_TITLE.'</a></li>';
			$links[] = '<li><a href="'.sefRelToAbs(YARBB_URL.'&amp;task=profile&amp;id='.$yarbb_user['id']).'">'._Y_YPROFILE_SETT.'</a></li>';


		}
	}
	// Are there any additional navlinks we should insert into the array before imploding it?
	if ($yarbb_config['o_additional_navlinks'] != '') {
		if (preg_match_all('#([0-9]+)\s*=\s*(.*?)\n#s', $yarbb_config['o_additional_navlinks']."\n", $extra_links)) {
			// Insert any additional links into the $links array (at the correct index)
			for ($i = 0; $i < count($extra_links[1]); ++$i) {
				array_splice($links, $extra_links[1][$i], 0, array('<li id="navextra'.($i + 1).'">'.$extra_links[2][$i]));
			}
		}
	}
	return ''."\n\t\t\t\t".implode(''."\n\t\t\t\t", $links).''."\n\t\t\t".'';
}

// Меню профиля
function generate_profile_menu($page = '') {
	global  $yarbb_config, $yarbb_user, $id;
	?>
<div>
	<h2><span><?php echo _Y_MYOPTIONS ?></span></h2>
	<div class="box" style="border:none;">
		<div class="inbox">
			<table width="100%" border="0" cellspacing="0" cellpadding="0">
				<tr>
					<td align="center" style="font-weight:bold"><div align="center"><a href="<?php echo sefRelToAbs(YARBB_URL.'&amp;task=profile&amp;section=display&amp;id='.$id); ?>"><?php echo _Y_DISPLAY; ?></a></div></td>
					<td align="center" style="font-weight:bold" ><div align="center"><a href="<?php echo sefRelToAbs(YARBB_URL.'&amp;task=profile&amp;section=privacy&amp;id='.$id); ?>"><?php echo _Y_PRIVOPT; ?></a></div></td>
					<td align="center" style="font-weight:bold" ><div align="center"><a href="<?php echo sefRelToAbs(YARBB_URL.'&amp;task=my_uploads&amp;id='.$id); ?>"><?php echo _Y_MYATTACH; ?></a>
						</div></td>
					<td align="center" style="font-weight:bold" >
						<div align="center">
								<?php if ($yarbb_user['g_id'] == YARBB_ADMIN || ($yarbb_user['g_id'] == YARBB_MOD && $yarbb_config['p_mod_ban_users'] == '1')): ?>
									<?php if ($page == 'admin')?>
							<a href="<?php echo sefRelToAbs(YARBB_URL.'&amp;task=profile&amp;section=admin&amp;id='.$id); ?>">
										<?php echo _Y_YARMODERS; ?></a><br />
								<?php endif; ?>
						</div></td>
				</tr>
			</table>
		</div>
	</div>
		<?php
	}
// Update posts, topics, last_post, last_post_id and last_poster for a forum (redirect topics are not included)
	function update_forum($forum_id) {
		$database = database::getInstance();

		$database->setQuery('SELECT COUNT(id), SUM(num_replies) FROM #__forum_topics WHERE moved_to IS NULL AND forum_id='.$forum_id);
		list($num_topics, $num_posts) = $database->loadRow();
		$num_posts = $num_posts + $num_topics;		// $num_posts is only the sum of all replies (we have to add the topic posts)
		$database->setQuery('SELECT last_post, last_post_id, last_poster FROM #__forum_topics WHERE forum_id='.$forum_id.' AND moved_to IS NULL ORDER BY last_post DESC LIMIT 1');
		$top = $database->loadAssocRow();

		if ( $top ) { // There are topics in the forum
			$database->setQuery('UPDATE #__forum_forums SET num_topics='.$num_topics.', num_posts='.$num_posts.', last_post='.$top['last_post'].', last_post_id='.$top['last_post_id'].', last_poster=\''.$top['last_poster'].'\' WHERE id='.$forum_id);
			$database->query();
		}else {	// There are no topics
			$database->setQuery('UPDATE #__forum_forums SET num_topics=0, num_posts=0, last_post=NULL, last_post_id=NULL, last_poster=NULL WHERE id='.$forum_id);
			$database->query();
		}

	}

// Movepost Mod 1.3 Block Start
// Update num_replies, poster, , posted, last_post, last_post_id, last_poster (and num_views if merged topics) for a topic
	function update_topic($topic_id, $num_views=0) {
		global $database;
		// Count number of replies in the topic
		//s
		$database->setQuery('SELECT COUNT(id) FROM #__forum_posts WHERE topic_id='.$topic_id);
		$num_replies = $database->loadResult() - 1;
		// Find the first poster and posted (could be different from the original topic)
		//$database->setQuery('SELECT poster, posted FROM #__forum_posts WHERE topic_id='.$topic_id.' ORDER BY posted LIMIT 1');
		//$database->query();
		// Last_post, last_post_id, last_poster (could be different from the original topic)
		$database->setQuery('SELECT posted, id, poster FROM #__forum_posts WHERE topic_id='.$topic_id.' ORDER BY posted DESC LIMIT 1');
		list($last_post, $last_post_id, $last_poster) = $database->loadRow();
		// Finally update the Topic
		//$database->setQuery('UPDATE #__forum_topics SET num_views=num_views+'.$num_views.',num_replies='.$num_replies.', poster=\''.$database->getEscaped($poster).'\', posted='.$posted.', last_post='.$last_post.', last_post_id='.$last_post_id.', last_poster=\''.$database->getEscaped($last_poster).'\' WHERE id='.$topic_id);
		//$database->query();
	}

// Movepost Mod 1.3 Block End
// Delete a topic and all of it's posts
	function delete_topic($topic_id) {
		global $database;
		// Delete the topic and any redirect topics
		//s
		$database->setQuery('DELETE FROM #__forum_topics WHERE id='.$topic_id.' OR moved_to='.$topic_id);
		$database->query();
		// Create a list of the post ID's in this topic
		$post_ids = '';
		//s
		$database->setQuery('SELECT id FROM #__forum_posts WHERE topic_id='.$topic_id);
		$rows=$database->loadRowList();

		foreach ($rows as $row)
			$post_ids .= ($post_ids != '') ? ','.$row[0] : $row[0];
		// Make sure we have a list of post ID's
		if ($post_ids != '') {
			//хрен его знает описания нет
			//	strip_search_index($post_ids);
			// Delete posts in topic
			$database->setQuery('DELETE FROM #__forum_posts WHERE topic_id='.$topic_id);
			$database->query();
		}
		// Delete any subscriptions for this topic
		$database->setQuery('DELETE FROM #__forum_subscriptions WHERE topic_id='.$topic_id);
		$database->query();
	}

// Delete a single post
	function delete_post($post_id, $topic_id) {
		global $database;
		//s
		$database->setQuery('SELECT id, poster, posted FROM #__forum_posts WHERE topic_id='.$topic_id.' ORDER BY id DESC LIMIT 2');
		$rows=$database->loadRowList();
		list($last_id, ,) = $rows[0];
		list($second_last_id, $second_poster, $second_posted) = $rows[1];
		// Delete the post
		$database->setQuery('DELETE FROM #__forum_posts WHERE id='.$post_id);
		$database->query();
//хрен его знает почему не описана
//s	strip_search_index($post_id);
		// Count number of replies in the topic
		//s
		$database->setQuery('SELECT COUNT(id) FROM #__forum_posts WHERE topic_id='.$topic_id);
		$num_replies = $database->loadResult() - 1;
		// If the message we deleted is the most recent in the topic (at the end of the topic)
		if ($last_id == $post_id) {
			// If there is a $second_last_id there is more than 1 reply to the topic
			if (!empty($second_last_id)) {
				//s
				$database->setQuery('UPDATE #__forum_topics SET last_post='.$second_posted.', last_post_id='.$second_last_id.', last_poster=\''.$database->getEscaped($second_poster).'\', num_replies='.$num_replies.' WHERE id='.$topic_id);
				$database->query();
			}
			else {
				// We deleted the only reply, so now last_post/last_post_id/last_poster is posted/id/poster from the topic itself
				$database->setQuery('UPDATE #__forum_topics SET last_post=posted, last_post_id=id, last_poster=poster, num_replies='.$num_replies.' WHERE id='.$topic_id);
				$database->query();
			}
		}
		else {
			// Otherwise we just decrement the reply counter
			$database->setQuery('UPDATE #__forum_topics SET num_replies='.$num_replies.' WHERE id='.$topic_id);
			$database->query();
		}
	}

// Replace censored words in $text
	function censor_words($text) {
		global $database;
		static $search_for, $replace_with;
		// If not already built in a previous call, build an array of censor words and their replacement text
		if (!isset($search_for)) {
			//s?
			$database->setQuery('SELECT search_for, replace_with FROM #__forum_censoring');
			$rows = $database->loadRowList();
			$search_for = array();
			$num_words = count($rows);

			for ($i = 0; $i < $num_words; ++$i) {
				list($search_for[$i], $replace_with[$i]) =$rows[$i];
				$search_for[$i] = '/\b('.str_replace('\*', '\w*?', preg_quote($search_for[$i], '/')).')\b/i';
			}
		}

		if (!empty($search_for)) {
			$text = substr(preg_replace($search_for, $replace_with, ' '.$text.' '), 1, -1);
		}
		return $text;
	}

// Determines the correct title for $user
// $user must contain the elements 'username', 'title', 'posts', 'g_id' and 'g_user_title'
	function get_title($user) {
		global $database, $yarbb_config, $yarbb_bans, $yarbb_admin_path, $cur_ban, $yarbb_path;
		static $ban_list, $yarbb_ranks;
		// If not already built in a previous call, build an array of lowercase banned usernames
		if (empty($ban_list)) {
			$ban_list = array();
			foreach ($yarbb_bans as $cur_ban)
				$ban_list[] = strtolower($cur_ban['username']);
		}
		// If not already loaded in a previous call, load the cached ranks
		if ($yarbb_config['o_ranks'] == '1' && empty($yarbb_ranks)) {
			@include $yarbb_admin_path.'/cache/cache_ranks.php';
			if (!defined('YARBB_RANKS_LOADED')) {
				require_once $yarbb_admin_path.'/include/cache.php';
				generate_ranks_cache();
				require $yarbb_admin_path.'/cache/cache_ranks.php';
			}
		}
		// If the user has a custom title
		if ( isset($user['title']) && $user['title'] != ''){
			$user_title = yarbb_htmlspecialchars($user['title']);
		}
		// If the user is banned
		else if (in_array(strtolower($user['username']), $ban_list))
			$user_title = _Y_BANNED;
		// If the user group has a default user title
		else if ($user['g_user_title'] != '')
			$user_title = yarbb_htmlspecialchars($user['g_user_title']);
		// If the user is a guest
		else if ($user['g_id'] == YARBB_GUEST)
			$user_title = _Y_YARGUEST ;
		else {
			// Are there any ranks?
			if ($yarbb_config['o_ranks'] == '1' && !empty($yarbb_ranks)) {
				@reset($yarbb_ranks);
				while (list(, $cur_rank) = @each($yarbb_ranks)) {
					if (intval($user['num_posts']) >= $cur_rank['min_posts'])
						$user_title = yarbb_htmlspecialchars($cur_rank['rank']);
				}
			}
			// If the user didn't "reach" any rank (or if ranks are disabled), we assign the default
			if (!isset($user_title))
				$user_title = _USERNAME;
		}
		return $user_title;
	}

//вывод постранички
	function paginate($num_pages, $cur_page, $link_to) {
		$pages = array();
		$link_to_all = false;
		$nav_links = true;
		// If $cur_page == -1, we link to all pages (used in viewforum.php)
		if ($cur_page == -1) {
			$cur_page = 1;
			$link_to_all = true;
			$nav_links = false;
		}
		if ($num_pages <= 1) {
			$pages = array('<strong>1</strong>');
		}else {
			if ($cur_page > 3) {
				$pages[] = '<a href="'.sefRelToAbs($link_to.'&amp;page=1').'">1</a>';
				if ($cur_page != 4) {
					$pages[] = '&hellip;';
				}
			}
			// Don't ask me how the following works. It just does, OK? :-)
			for ($current = $cur_page - 2, $stop = $cur_page + 3; $current < $stop; ++$current) {
				if ($current < 1 || $current > $num_pages)
					continue;
				else if ($current != $cur_page || $link_to_all)
					$pages[] = '<a href="'.sefRelToAbs($link_to.'&amp;page='.$current).'">'.$current.'</a>';
				else
					$pages[] = '<strong>'.$current.'</strong>';
			}
			if ($cur_page <= ($num_pages-3)) {
				if ($cur_page != ($num_pages-3))
					$pages[] = '&hellip;';
				$pages[] = '<a href="'.sefRelToAbs($link_to.'&amp;page='.$num_pages).'">'.$num_pages.'</a>';
			}
		}
		if($nav_links) {
			if($cur_page > 1) {
				$back_page_number = $cur_page-1;
				$back_page = '<a href="'.sefRelToAbs($link_to.'&amp;page='.$back_page_number).'">&laquo;--</a>';
				array_splice($pages, 0, 0, $back_page);
			}
			if($cur_page < $num_pages) {
				$next_page_number =  $cur_page +1;
				$next_page = '<a href="'.sefRelToAbs($link_to.'&amp;page='.$next_page_number).'">--&raquo;&nbsp;</a>';
				array_push($pages, $next_page);
			}
		}
		return implode('&nbsp;', $pages);
	}

// Формат времени и даты
	function format_time($timestamp, $date_only = false) {
		global $yarbb_config, $yarbb_user;
		if ($timestamp == ''){
			return _NEVER;
		}
		$now = time();
		$date = date($yarbb_config['o_date_format'], $timestamp);
		$today = date($yarbb_config['o_date_format'], $now);
		$yesterday = date($yarbb_config['o_date_format'], $now-86400);
		if ($date == $today)
			$date = _Y_TODAY;
		else if ($date == $yesterday)
			$date = _Y_YESTODAY;
		if (!$date_only)
			return $date.' '.date($yarbb_config['o_time_format'], $timestamp);
		else
			return $date;
	}

// If we are running pre PHP 4.3.0, we add our own implementation of file_get_contents
	if (!function_exists('file_get_contents')) {
		function file_get_contents($filename, $use_include_path = 0) {
			$data = '';
			if ($fh = fopen($filename, 'rb', $use_include_path)) {
				$data = fread($fh, filesize($filename));
				fclose($fh);
			}
			return $data;
		}
	}

// Compute a hash of $str
// Uses sha1() if available. If not, SHA1 through mhash() if available. If not, fall back on md5().
	function yarbb_hash($str) {
		if (function_exists('sha1'))	// Only in PHP 4.3.0+
			return sha1($str);
		else if (function_exists('mhash'))	// Only if Mhash library is loaded
			return bin2hex(mhash(MHASH_SHA1, $str));
		else
			return md5($str);
	}
// Try to determine the correct remote IP-address
	function get_remote_address() {
		return $_SERVER['REMOTE_ADDR'];
	}
// Equivalent to htmlspecialchars(), but allows &#[0-9]+ (for unicode)
	function yarbb_htmlspecialchars($str) {
		$str = preg_replace('/&(?!#[0-9]+;)/s', '&amp;', $str);
		$str = str_replace(array('<', '>', '"'), array('&lt;', '&gt;', '&quot;'), $str);
		return $str;
	}
// Equivalent to strlen(), but counts &#[0-9]+ as one character (for unicode)
	function yarbb_strlen($str) {
		return strlen(preg_replace('/&#([0-9]+);/', '!', $str));
	}
// Convert \r\n and \r to \n
	function yarbb_linebreaks($str) {
		return str_replace("\r", "\n", str_replace("\r\n", "\n", $str));
	}

// A more aggressive version of trim()
	function yarbb_trim($str) {

		if (strpos('utf-8', '8859') !== false) {
			$fishy_chars = array(chr(0x81), chr(0x8D), chr(0x8F), chr(0x90), chr(0x9D), chr(0xA0));
			return trim(str_replace($fishy_chars, ' ', $str));
		}
		else
			return trim($str);
	}

// Dump contents of variable(s)
	function dump() {
		echo '<pre>';
		$num_args = func_num_args();
		for ($i = 0; $i < $num_args; ++$i) {
			print_r(func_get_arg($i));
			echo "\n\n";
		}
		echo '</pre>';
		exit;
	}

	define( 'search_label_url', YARBB_URL.'&amp;task=search&amp;action=show_label&amp;text=');
	function show_labels($labels, $url= search_label_url) {
		global $search_label_url;

		$s = null;
		if (!empty($labels)) {
			$lab_array = explode_labels($labels);
			for($k=0; $k<count($lab_array); $k++)
				$lab_array[$k] = '<a href="'.sefRelToAbs($url.urlencode($lab_array[$k])).'">'.yarbb_htmlspecialchars($lab_array[$k]).'+</a>';
			$s = implode(', ', $lab_array);
			unset($lab_array);
		}
		return $s;
	}

	function get_microtime() {
		list($usec, $sec) = explode(' ', microtime());
		return ((float)$usec + (float)$sec);
	}